<?php

namespace app\common\model;

use app\common\model\user\Address;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'state_text',
        'status_text',
        'image_str',
        'images_array',

    ];

    public function getImagesArrayAttr($value, $data)
    {
        $arr = explode(',', $data['images']);
        foreach ($arr as &$v) {
            $v = cdnurl($v, true);
        }
        return $arr;
    }
    public static function getCartNum($goods_id, $user_id)
    {
        return Cart::where('goods_id',$goods_id)->where('user_id',$user_id)->value('num')??0;
    }

    public function getImageStrAttr($value, $data)
    {
        return $data['image'] ? cdnurl($data['image'], true) : '';
    }


    public function getStateList()
    {
        return ['1' => __('State 1'), '2' => __('State 2')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function review()
    {
        return $this->hasMany('app\common\model\goods\Review', 'goods_id', 'id', [], 'LEFT');
    }

    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public static function reduceInventory($goods_id, $num)
    {
        $stock = self::where('id', $goods_id)->value('stock');
        if ($stock < $num) {
            exception('库存不足');
        }
        return self::where('id', $goods_id)->dec('stock', $num)->inc('sales', $num)->update();
    }
    public static function stockUp($goods_id, $num)
    {
        return self::where('id', $goods_id)->inc('stock', $num)->dec('sales', $num)->update();
    }
}
